package com.gan.simple_init.util;

import com.gan.simple_init.common.constant.RedisConstant;
import com.gan.simple_init.common.exception.BusinessException;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class JwtTokenUtil {

    private static final String CLAIM_KEY_CREATED = "created";

    /**
     * 加密时使用的密钥
     */
    @Value("${jwt.secret}")
    private String secret;

    /**
     * 过期时间
     */
    @Value("${jwt.expiration}")
    private Long expiration;


    private static RedisUtil redisUtil;

    @Resource
    public void setRedisService(RedisUtil redisUtil) {
        JwtTokenUtil.redisUtil = redisUtil;
    }

    /**
     * 根据用户信息生成token
     *
     * @param userDetails 用户信息
     * @return String
     */
    public String generateToken(UserDetails userDetails, Long id) {
        //将用户名和创建时间分别放入key为'CLAIM_KEY_USERNAME'和'CLAIM_KEY_CREATED'的map中
        Map<String, Object> map = new HashMap<>();
        map.put("userName", userDetails.getUsername());
        map.put(CLAIM_KEY_CREATED, new Date());
        map.put("id", id.toString());
        return generateToken(map);
    }

    /**
     * 根据荷载生成token信息
     *
     * @param map 荷载信息
     * @return String
     */
    private String generateToken(Map<String, Object> map) {
        return Jwts.builder()
                // 设置荷载
                .setClaims(map)
                // 设置创建时间
                .setExpiration(generateTokenExpiration())
                // 使用SHA256withDSA加密算法
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    /**
     * 获取token创建时间
     *
     * @return Date
     */
    private Date generateTokenExpiration() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 获取用户username
     *
     * @param token 令牌
     * @return String token
     */
    public String getUserNameFromToken(String token) {
        try {
            Object userName = getClaimsFromToken(token).get("userName");
            if (Objects.nonNull(userName)) {
                return userName.toString();
            } else {
                return null;
            }
        } catch (Exception e) {
            log.error("token 获取用户名失败!");
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 获取用户id
     *
     * @param token 令牌
     * @return String id
     */
    public Long getUserIdFromToken(String token) {
        try {
            if (Objects.isNull(getClaimsFromToken(token).get("id"))) {
                return null;
            } else {
                return Long.parseLong((String) getClaimsFromToken(token).get("id"));
            }
        } catch (ExpiredJwtException e) {
            log.error("token 获取 id 失败!");
            throw new BusinessException("token 获取 id 失败!");
        }
    }


    /**
     * 从token中获取荷载
     *
     * @param token 令牌
     * @return Claims
     */
    public Claims getClaimsFromToken(String token) {
        try {
            return Jwts.parser()
                    // 使用密钥解密
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("token或密钥无效!");
            throw new BusinessException("token或密钥无效!");
        }
    }

    /**
     * 验证用户token是否有效
     *
     * @param token       令牌
     * @param userDetails 用户信息
     * @return boolean
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        Long id = getUserIdFromToken(token);
        if (StringUtils.isEmpty(username) || Objects.isNull(id)) {
            return false;
        }
        return username.equals(userDetails.getUsername()) && isTokenExpired(token);
    }

    /**
     * 判断token是否过期
     *
     * @param token 令牌
     * @return boolean
     */
    public boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        if (Objects.nonNull(expiredDate)) {
            return !expiredDate.before(new Date());
        } else {
            return false;
        }
    }

    /**
     * 在token中获取失效时间
     *
     * @param token 令牌
     * @return Date
     */
    public Date getExpiredDateFromToken(String token) {
        try {
            return getClaimsFromToken(token).getExpiration();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 判断token是否可以被刷新
     *
     * @param token 令牌
     * @return boolean
     */
    public boolean canRefresh(String token) {
        return isTokenExpired(token);
    }

    /**
     * 刷新token有效时间
     *
     * @param token 令牌
     * @return String
     */
    public String refreshToken(String token) {
        Claims claimsFromToken = getClaimsFromToken(token);
        claimsFromToken.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claimsFromToken);
    }

    /**
     * 根据请求头移除redis中的token
     *
     * @param httpServletRequest http请求
     */
    public void removeRedisToken(HttpServletRequest httpServletRequest) {
        // 获取token
        String token = httpServletRequest.getHeader("token");
        if (StringUtils.isNotEmpty(token)) {
            // 获取当前登陆用户username
            String userName = this.getUserNameFromToken(token);
            if (StringUtils.isNotEmpty(userName)) {
                redisUtil.del(RedisConstant.USER_LOGIN_KEY + token);
            } else {
                throw new BusinessException("当前没有用户登录!");
            }
        }
    }

    /**
     * 获取token是否存在redis中
     *
     * @param token 令牌信息
     * @return boolean
     */
    public boolean getTokenFlag(String token) {
        return Objects.nonNull(redisUtil.get(RedisConstant.USER_LOGIN_KEY + token));
    }
}
